package myreflect6;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @Author:CJJ
 * @Date:2025/5/6
 * @Description:反射动态创建对象
 */
public class MyReflectDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        /**
         * 反射可以跟配置文件结合的方式,动态的创建对象,并调用方法
         */
        
        //1.读取配置文件中的信息
        Properties prop = new Properties();
        FileInputStream stream = new FileInputStream("src/test/prop.properties.properties");
        prop.load(stream);
        stream.close();
        System.out.println(prop);

         //2.获取全类名和方法名
        String classname = (String) prop.get("classname");
        String methodName = (String) prop.get("method");
        System.out.println(classname);
        System.out.println(methodName);

        //3.利用反射创建对象并运行方法
        Class cls = Class.forName(classname);

        //4.获取构造方法
        Constructor con = cls.getDeclaredConstructor();
       Object obj = con.newInstance();
        System.out.println(obj);

        //获取成员方法并运行
        Method method = cls.getDeclaredMethod(methodName);
        method.setAccessible(true);
        method.invoke(obj);
    }
}
